package com.journey.org.ui.knowledge.play.list

import android.app.Application
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import androidx.databinding.ObservableInt
import androidx.lifecycle.viewModelScope
import com.journey.org.BR
import com.journey.org.R
import com.journey.org.app.HttpManager
import com.journey.org.app.requestHttpManager
import com.journey.org.app.requestPlayAndroid
import com.journey.org.entity.PlayAndroidProjectEntity
import com.mvvmhabit.org.base.BaseViewModel
import com.mvvmhabit.org.binding.command.BindingAction
import com.mvvmhabit.org.binding.command.BindingCommand
import com.mvvmhabit.org.custom.LoadingLayout
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import me.tatarka.bindingcollectionadapter2.ItemBinding

/**
 * @Date: 2020/12/18 10:31
 * @Author:小妖
 * @Description: play Android 项目列表
 */
class PlayAndroidListViewModel(application: Application) : BaseViewModel(application) {

    var page = 1

    val onIdField = ObservableField<String>()

    val onClickAgainLoadCommand = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            page = 1
            loadPlayAndroidList(onIdField.get()!!)
        }
    })

    val onLoadMoreCommand = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            ++page
            loadPlayAndroidList(onIdField.get()!!)
        }
    })

    val onRefreshCommand = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            page = 1
            loadPlayAndroidList(onIdField.get()!!)
        }
    })

    val itemBinding =
        ItemBinding.of<PlayAndroidListItemViewModel>(BR.viewModel, R.layout.play_android_list_item)

    val items = ObservableArrayList<PlayAndroidListItemViewModel>()

    fun loadPlayAndroidList(id: String) {
        if (page == 1) {
            showLoadDialog()
            items.clear()
        }
        requestPlayAndroid<PlayAndroidProjectEntity> {
            requestHttpManager {
                onLoader {
                    HttpManager.getInstance().loadPlayAndroidListById(page, id)!!
                }
                onSuccess {
                    if (it.datas.isNotEmpty()) {
                        it.datas.forEach { entity ->
                            items.add(
                                PlayAndroidListItemViewModel(
                                    this@PlayAndroidListViewModel,
                                    entity
                                )
                            )
                        }
                    }
                }
                onComplete {
                    dismissLoadDialog()
                }
            }
        }
    }
}